package com.dippy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dippy.common.Result;
import com.dippy.entity.Book;
import com.dippy.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin// 跨域
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    // @Autowired
    // private BookDao bookDao;
    // @GetMapping("/findAll")
    // public List<Book> findAll() {
    //     return bookDao.selectList(null);
    // }

    @GetMapping("/findAll/{current}/{size}")
    public Result findAll(@PathVariable("current") Integer currentPage,@PathVariable("size") Integer size) {
        Page<Book> page = new Page<>( currentPage, size);
        IPage<Book> bookIPage = bookService.page(page, new QueryWrapper<Book>());

        return Result.succ(bookIPage);
    }

    @PostMapping("/addBook")
    public Result addBook(@RequestBody Book book) {

        boolean update = bookService.saveOrUpdate(book);

        // 添加失败
        if (!update)
            return Result.fail("添加失败");
        // 添加成功
        return Result.succ("添加成功");
    }

    @GetMapping("/findBookById/{id}")
    public Result findBookById(@PathVariable("id") Integer id) {
        Book book = bookService.getById(id);
        if (book == null)
            return Result.fail("id不存在");
        return Result.succ(book);
    }

    @PutMapping("/updateBook")
    public Result updateBookById(@RequestBody Book book) {
        if (book.getId()== null){
            return Result.fail("修改失败");
        }
        boolean update = bookService.saveOrUpdate(book);
        if (!update)  return Result.fail("修改失败");
        return Result.succ("修改成功");
    }

    @DeleteMapping("/deleteBookById/{id}")
    public Result deleteBookById(@PathVariable("id")Integer id) {
        // 判断id有效，是否为空
        if (id == null) return Result.fail("删除失败");
        // 根据id删除
        boolean delete = bookService.removeById(id);
        // 删除失败，显示无此数据
        if (!delete) return Result.fail("无此数据");
        // 删除成功
        return  Result.succ("删除成功");
    }
}
